import { Button, Swiper, SwiperItem, View,Image,Text } from '@tarojs/components'
import React, { useEffect, useState } from 'react'
import Taro, { useDidShow, useReachBottom, useShareAppMessage } from '@tarojs/taro'
import './index.scss'

export default function Index() {
  let capsuleInfo = {}
  if(process.env.TARO_ENV === 'weapp') capsuleInfo = Taro.getMenuButtonBoundingClientRect()

  let moreMap = {
    'more':'加载更多',
    'loading':'加载中~',
    'no-more':'已经到底啦~',
  }
  const [curTabs, setcurTabs] = useState(0)
  const [tabsList,setTabsList] = useState([])
  const [hotList,setHotList] = useState([])
  const [swiperList,setSwiperList] = useState('')
  const [params,setParams] = useState({
    page:1,
    pageSize:10
  })
  const [moreStatus,setmoreStatus] = useState()
  const [location,setLocation] = useState({})
  const [otherList,setOtherList] = useState([])

  useEffect(()=>{
    _initData()
  },[])
  useDidShow(()=>{
    Taro.eventCenter.off('updateLocation')
    Taro.eventCenter.on('updateLocation',(res)=>{
      updateLocation()
      init()
    })
    updateLocation()
  })
  useReachBottom(()=>{
    if(params.total > hotList.length){
      _getHotList({page:params.page+1},e=>{
        setHotList([...hotList,...e.records])
      })
    }else{
      setmoreStatus("no-more")
    }
  })
  function updateLocation(){
    const loca = Taro.getStorageSync('cityInfo')
    if(loca && loca.cityCode){
      setLocation(loca || {})
    }
  }
  const handleTabs = e=>{
    setcurTabs(e)
    _getHotList({page:1,...tabsList[e]})
  }
  function handleToDetail(e){  ///   跳详情
    Taro.navigateTo({
      url:`/mainPages/event-detail/index?id=${e.id}`
    })
  }
  
  ///      network
  const _initData = async ()=>{
    const {router} = Taro.getCurrentInstance()
    _getTabsList(router.params.id)
  }
  const _getTabsList = e=>{
    if(e){
      Taro.$get('/act/gather/topic',{
        cityCode:Taro.getStorageSync('cityInfo')?.cityCode||'0',
        flag:'0',
        typeId:e
      }).then(res=>{
        setTabsList(res.content.topicList || [])
        setSwiperList(res.content.gatherJsons.filter(res=>res.typeId == e)?.[0]?.bigUrl)
        if(res.content.topicList.length){
          _getHotList({page:1,...res.content.topicList[0]})
        }
      })
      return;
    }
    Taro.$toast('缺少主要参数:TypeId')
  }
  const _getHotList = async (e,func)=>{  //  获取活动列表
    const loca = Taro.getStorageSync('cityInfo')
    setmoreStatus('more')
    Taro.showLoading({
      title:'加载中...'
    })
    const data = {
      ...params,
      cityCode:loca.cityCode||'0',
      page:params.page,
      pageSize:params.pageSize,
      topicIds:e?.topicId || params?.topicIds,
      ...e
    }
    if(loca && loca.latitude){
      Object.assign(data,{
        latitude:loca.latitude,
        longitude:loca.longitude
      })
    }
    const res = await Taro.$post('/act/gather/list',data,'1')
    if(res.code == '1'){
      if(res.content.total < 10){
        _getOtherEvent(e)
      }
      setParams({...data,total:res.content.total})
      setmoreStatus('no-more')
      if(func){
        func(res.content)
        return;
      }
      setHotList(res.content.records)
    }
  }
  function _getOtherEvent(values){  ///  获取其他城市列表
    const loca = Taro.getStorageSync('cityInfo')
    setmoreStatus('loading')
    let data = {
      dateStr:values.dateStr,
      topicIds:values.topicId
    }
    if(loca && loca.latitude){
      Object.assign(data,{
        cityCode:loca.cityCode,
        latitude:loca.latitude,
        longitude:loca.longitude
      })
    }
    Taro.$post('/act/gather/otherCity',data).then(result=>{
      if(result.code === '1'){
        setOtherList(result.content)
        setmoreStatus('no-more')
      }
    })
  }
  
  return (
  <View>
    <View className={`home ${process.env.TARO_ENV == 'tt'?'tt':''}`} style={process.env.TARO_ENV == 'h5'?{paddingTop:40}:null}>
      <View class="home-crumbs" style={process.env.TARO_ENV == 'h5'?{paddingTop:0}:null}>
        <View className="at-icon at-icon-chevron-left" onClick={()=>{
          Taro.navigateBack().catch(e=>{
            Taro.reLaunch({
              url:'/pages/index/index'
            })
          })
        }}></View>
        <View class="crumbs-main">
          <Image src={require('@/static/Location.svg')} class="main-logo"></Image>
          <View className='h2' style={{whiteSpace:'nowrap'}} onClick={()=>{
            Taro.navigateTo({
              url:'/mainPages/city-list/index'
            })
          }}>{location.name?.replace("市", "") || '全国'}</View>
          <View className="at-icon at-icon-chevron-down" style={{fontSize:14}}></View>
        </View>
        {process.env.TARO_ENV == 'tt'?null:<>
        <View style={{width: capsuleInfo.width+'px'}}></View>
        </>}
      </View>

      <View className='home-swiper'><Image className="swiper-img" src={swiperList} mode="aspectFill"></Image></View>

      {tabsList.length?<>
      <View className="home-tabs">
        <View className="tabs-list not-bar">
          {tabsList?.map((item,idx)=>{
            return <View className={`tabs-item ${curTabs == idx?'active':''}` } key={item.id} onClick={()=>{handleTabs(idx)}}>
            <View className='item-h2'>{item.dateStr}</View> <Text>{item.dateDesc}</Text>
          </View>
          })}
        </View>
      </View>
      <View className="home-screen">
        {showDrop == 'activity'?
        <View className="item-drop">
          <View className="drop-activity">
            <View className="drop-list" onClick={()=>{
              if(item.appId){
                Taro.navigateToMiniProgram({
                  appId: item.appId,
                  path: item.urlPath,
                })
                return;
              }
              Taro.navigateTo({
                url:`/mainPages/zone/index?id=${item.typeId}`
              })
            }}>世界锦标赛</View>
          </View>
        </View>:null}
        {showDrop == 'sort'?
        <View className="item-drop">
          <View className="drop-sort">
            <View className={`drop-list ${params.sort == 0?'active':''}`} onClick={()=>{
              setParams({...params,sort:0})
            }}>离我最近</View>
            <View className={`drop-list ${params.sort == 1?'active':''}`} onClick={()=>{
              setParams({...params,sort:1})
            }}>价格最低</View>
          </View>
        </View>:null}
        <View className='screen-item' onClick={()=>{
          Taro.navigateTo({
            url:'/mainPages/city-list/index'
          })
        }}>{location.name?.replace("市", "") || '全国'} <View className="at-icon at-icon-chevron-down" style={{fontSize:14}}></View></View>
        <View className={`screen-item ${showDrop == 'activity'?'theme-color':''}`} onClick={()=>{
          setshowDrop(null)
          if(showDrop!='activity'){
            setshowDrop('activity')
          }
        }}>全部活动 <View className="at-icon at-icon-chevron-down" style={{fontSize:14}}></View></View>
        <View className={`screen-item ${showDrop == 'sort'?'theme-color':''}`} onClick={()=>{
          setshowDrop(null)
          if(showDrop!='sort'){
            setshowDrop('sort')
          }
        }}>{params.sort == '1'?'价格最低':'离我最近'} <View className="at-icon at-icon-chevron-down" style={{fontSize:14}}></View></View>
      </View>
      </>:<View className='var-empty'>
        <View className="h2">「{location.name?.replace("市", "") || '全国'}」最近没有场次安排</View>
        <View className="p">后续会发布新的活动场次，敬请期待哦~</View>
      </View>}

      {hotList.length?<View className="home-hot">
        {hotList.map(item=>{
          return <View className="hot-list" key={item.id} onClick={()=>{handleToDetail(item)}}>
            <View className="hot-item">
              <View className="item-img">
                {item.sellOut?<View className="item-mask"><Image className="mask-img" src={require('../../static/soldout.png')}></Image></View>:null}
                <Image className="img-pic" src={Taro.getMedia(item.logoUrl)} mode="aspectFill"></Image>
              </View>
              <View className="item-info">
                <View className="dot h2">{item.locationName}</View>
                {item.tagsJson?
                <View className="info-list">
                  {item.tagsJson.map(tag=>{
                    return <Text className={`${tag.source == 'PLATFORM'?'red':''}`} key={tag.tagName}>{tag.tagName}</Text>
                  })}
                </View>:null}
                <View className="h4 dot"><Image src={require('@/static/icon_calendar.png')} /> {item.dateStr}</View>
                {item.hallName?<View className="h4 dot"><Image src={require('@/static/icon-space.png')} /> {item.hallName}</View>:null}
                <View className="h4"><Image src={require('@/static/icon_map-pin.png')} />{item.distance?<Text style={{marginRight:4}}>{item.distance}</Text>:''}<Text className='dot'>{item.locationAddress}</Text></View>
              
                <View className="list-item">
                  {item.isEstablish?<>
                  <Image className='image' src={require('@/static/checked-true.svg')}></Image>
                  <Text className='strong'>已成团</Text>
                  <Text className='span'>已报名{item.recordNum}人{item.maxTickets?`（满场${item.maxTickets}人）`:null}</Text>
                  </>:<>
                  <Text className='strong'>{item.establishTickets}人开场{item.recordNum>0?'，已组'+item.recordNum+'人':''}</Text>
                  <Text className='span'>{item.remainTimeDesc}</Text>
                  </>}
                </View>
              </View>
            </View>
            <View className="item-footer">
              <View className="footer-merchant">
                <Image className='logo' src={item.merchantUrl} />
                <View>{item.merchantName}</View>
                <Image className='icon' src={require('@/static/verified.png')} />
              </View>
              <View className="footer-price">¥ <Text style={{fontSize:18,margin:"0 1px"}}>{item.price}</Text> {item.areaPrice=='2'?'起':''}</View>
            </View>
          </View>
        })}
      </View>:null}
      {otherList?.length && location.cityCode != '0'?<>
        <View className="other-title h2">其他城市活动</View>
        <View className="home-hot">
          {otherList.map(item=>{
            return <View className="hot-list" key={item.id} onClick={()=>{handleToDetail(item)}}>
            <View className="hot-item">
              <View className="item-img">
                {item.sellOut?<View className="item-mask"><Image className="mask-img" src={require('../../static/soldout.png')}></Image></View>:null}
                <Image className="img-pic" src={Taro.getMedia(item.logoUrl)} mode="aspectFill"></Image>
              </View>
              <View className="item-info">
                <View className="dot h2">{item.locationName}</View>
                {item.tagsJson?
                <View className="info-list">
                  {item.tagsJson.map(tag=>{
                    return <Text className={`${tag.source == 'PLATFORM'?'red':''}`} key={tag.tagName}>{tag.tagName}</Text>
                  })}
                </View>:null}
                <View className="h4 dot"><Image src={require('@/static/icon_calendar.png')} /> {item.dateStr}</View>
                {item.hallName?<View className="h4 dot"><Image src={require('@/static/icon-space.png')} /> {item.hallName}</View>:null}
                <View className="h4"><Image src={require('@/static/icon_map-pin.png')} />{item.distance?<Text style={{marginRight:4}}>{item.distance}</Text>:''}<Text className='dot'>{item.locationAddress}</Text></View>
              
                <View className="list-item">
                  {item.isEstablish?<>
                  <Image className='image' src={require('@/static/checked-true.svg')}></Image>
                  <Text className='strong'>已成团</Text>
                  <Text className='span'>已报名{item.recordNum}人{item.maxTickets?`（满场${item.maxTickets}人）`:null}</Text>
                  </>:<>
                  <Text className='strong'>{item.establishTickets}人开场{item.recordNum>0?'，已组'+item.recordNum+'人':''}</Text>
                  <Text className='span'>{item.remainTimeDesc}</Text>
                  </>}
                </View>
              </View>
            </View>
            <View className="item-footer">
              <View className="footer-merchant">
                <Image className='logo' src={item.merchantUrl} />
                <View>{item.merchantName}</View>
                <Image className='icon' src={require('@/static/verified.png')} />
              </View>
              <View className="footer-price">¥ <Text style={{fontSize:18,margin:"0 1px"}}>{item.price}</Text> {item.areaPrice=='2'?'起':''}</View>
            </View>
          </View>
          })}
        </View>
      </>:null}
      {hotList.length && moreStatus?<View className="var-more">{moreMap[moreStatus]}</View>:null}
    </View>
  </View>
  )
}
